/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pl.tewi.jeeunit.junit4.statements;

import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.Statement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pl.tewi.jeeunit.annotations.RunAs;
import pl.tewi.jeeunit.contexts.ApplicationServerContext;
import pl.tewi.jeeunit.controller.ServerControllerFactory;
import pl.tewi.jeeunit.controllers.ServerController;
import pl.tewi.jeeunit.exceptions.AuthenticationException;

/**
 *
 * @author Marcin Kwapisz
 */
public class Login extends BaseFrameworkStatement {

    private static final Logger LOGGER = LoggerFactory.getLogger(Login.class.getName());
    private final FrameworkMethod method;

    /**
     * 
     * @param fNext
     * @param context
     * @param method
     */
    public Login(final Statement fNext, final ApplicationServerContext context, final FrameworkMethod method) {
        super(fNext, context);
        this.method = method;
    }

    @Override
    public void evaluate() throws Throwable {
        RunAs runas = method.getAnnotation(RunAs.class);
        LOGGER.debug("Login");
        if (runas != null) {
            ServerController controller = ServerControllerFactory.getServerController(applicationServerContext);
            try {
                controller.login(runas.value(), runas.value());
                LOGGER.info("User logged in as {}", runas.value());
            } catch (AuthenticationException ex) {
                //połknięcie wyjątku logowania konieczne by wykonała się ewaluacja następnych statementów
                LOGGER.error("User not logged in. User does not exists in declared security realm");
            }
        }

        fNext.evaluate();
    }
}
